package com.shop.auth.service;

import com.shop.auth.client.UserClient;
import com.shop.auth.config.JwtProperties;
import com.shop.auth.pojo.UserInfo;
import com.shop.auth.utils.JwtUtils;
import com.shop.common.exception.ShopException;
import com.shop.user.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

/**
 * @author : Created by HGL on 2019/03/29 14:18
 * @version : 1.0
 * Description :
 */
@Slf4j
@Service
@EnableConfigurationProperties(JwtProperties.class)
public class AuthService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private JwtProperties prop;

    public String login(String username, String password) {
        //校验用户名和密码
        User user = userClient.queryUser(username, password);
        //判断
        if (user == null) {
            throw new ShopException("用户名或密码有误！");
        }
        //生成token
        try {
            String token = JwtUtils.generateToken(new UserInfo(user.getId(), username), prop.getPrivateKey(), prop.getExpire());
            return token;
        } catch (Exception e) {
            log.error("[授权中心]用户名或密码有误，用户名：{}",username,e);
            throw new ShopException("用户名或密码有误！");
        }
    }
}
